<template>
  <view class="customer-service">
    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-container" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      :scroll-into-view="scrollToView"
    >
      <view class="chat-list">
        <!-- 欢迎消息 -->
        <view class="message system">
          <text>您好，我是荷叶健康智能助手，请问有什么可以帮您？</text>
        </view>

<!--        gyh-->
        
        <!-- 消息列表 -->
        <view 
          v-for="(item, index) in messageList" 
          :key="index"
          :id="'msg-' + index"
          class="message"
          :class="item.type"
        >
          <!-- 用户头像 -->
          <image 
            v-if="item.type === 'user'" 
            class="avatar"
            :src="userInfo && userInfo.headImgUrl ? userInfo.headImgUrl : '/static/img/user-avatar.png'"
          ></image>
          
          <!-- AI助手头像 -->
          <image 
            v-else 
            class="avatar"
            src="/static/img/ai-avatar.png"
          ></image>
          
          <!-- 消息内容 -->
          <view class="content">
            <text>{{item.content}}</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-container">
      <input 
        type="text"
        v-model="inputMessage"
        placeholder="请输入您的问题"
        @confirm="sendMessage"
      />
      <button 
        class="send-btn"
        @tap="sendMessage"
        :disabled="!inputMessage.trim() || isLoading"
      >{{isLoading ? '发送中...' : '发送'}}</button>
    </view>
  </view>
</template>

<script>
import { customerServiceApi } from '@/api/customer-service'

export default {
  data() {
    return {
      inputMessage: '',
      messageList: [],
      scrollTop: 0,
      scrollToView: '',
      isLoading: false,
      userInfo: null
    }
  },
  onLoad() {
    // 获取用户信息
    this.getUserInfo();
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
          this.userInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo;
        }
      } catch (e) {
        console.error('获取用户信息失败:', e);
      }
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return;
      
      // 添加用户消息
      const userMessage = {
        type: 'user',
        content: this.inputMessage
      };
      this.messageList.push(userMessage);
      
      // 清空输入框
      const message = this.inputMessage;
      this.inputMessage = '';
      
      // 自动滚动到底部
      this.scrollToBottom();
      
      try {
        this.isLoading = true;
        // 调用封装的AI接口
        const response = await customerServiceApi.sendMessage(message);
        
        console.log('AI响应:', response);
        
        // 添加AI回复
        if (response.code === 200) {
          // 解析返回的JSON字符串
          try {
            const parsedData = JSON.parse(response.data);
            // 提取AI回复的content内容并移除<think>标签
            let aiContent = parsedData.message?.content || '抱歉，我无法理解您的问题';
            
            // 移除<think>标签及其内容
            aiContent = aiContent.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
            
            this.messageList.push({
              type: 'ai',
              content: aiContent
            });
          } catch (parseError) {
            console.error('解析AI响应失败:', parseError);
            this.messageList.push({
              type: 'ai',
              content: response.data || '抱歉，我无法理解您的问题'
            });
          }
        } else {
          throw new Error(response.msg || '请求失败');
        }
      } catch (error) {
        console.error('请求错误:', error);
        // 显示错误消息
        uni.showToast({
          title: error.message || '网络错误',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
      
      // 滚动到最新消息
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    
    // 滚动到底部
    scrollToBottom() {
      if (this.messageList.length > 0) {
        this.scrollToView = 'msg-' + (this.messageList.length - 1);
      }
    }
  }
}
</script>

<style lang="scss">
.customer-service {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  
  .chat-container {
    flex: 1;
    padding: 20rpx;
    
    .chat-list {
      .message {
        display: flex;
        margin-bottom: 30rpx;
        
        &.system {
          justify-content: center;
          
          text {
            background-color: rgba(0, 0, 0, 0.1);
            padding: 10rpx 20rpx;
            border-radius: 10rpx;
            font-size: 24rpx;
            color: #666;
          }
        }
        
        &.user {
          flex-direction: row-reverse;
          
          .content {
            background-color: #007AFF;
            color: #fff;
            margin-right: 20rpx;
            margin-left: 100rpx;
            
            &:after {
              right: -16rpx;
              border-left-color: #007AFF;
            }
          }
        }
        
        &.ai {
          .content {
            background-color: #fff;
            margin-left: 20rpx;
            margin-right: 100rpx;
            
            &:after {
              left: -16rpx;
              border-right-color: #fff;
            }
          }
        }
        
        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
        }
        
        .content {
          position: relative;
          padding: 20rpx;
          border-radius: 10rpx;
          max-width: 60%;
          word-break: break-all;
          
          &:after {
            content: '';
            position: absolute;
            top: 20rpx;
            border: 8rpx solid transparent;
          }
        }
      }
    }
  }
  
  .input-container {
    background-color: #fff;
    padding: 20rpx;
    display: flex;
    align-items: center;
    border-top: 1rpx solid #eee;
    
    input {
      flex: 1;
      height: 72rpx;
      background-color: #f5f5f5;
      border-radius: 36rpx;
      padding: 0 30rpx;
      margin-right: 20rpx;
      font-size: 28rpx;
    }
    
    .send-btn {
      width: 120rpx;
      height: 72rpx;
      line-height: 72rpx;
      text-align: center;
      background-color: #007AFF;
      color: #fff;
      border-radius: 36rpx;
      font-size: 28rpx;
      
      &[disabled] {
        background-color: #ccc;
      }
    }
  }
}
</style> 